//
//  SWOauthViewController.swift
//  SinaWeibo
//
//  Created by AenyMo on 16/3/31.
//  Copyright © 2016年 AenyMo. All rights reserved.
//

import UIKit
import SVProgressHUD

class SWOauthViewController: UIViewController {
    
    //定义webView属性
    let webView = UIWebView()
    
    //MARK: - 监听事件
    //关闭授权页
    @objc private func closeOauth() {
        
        dismissViewControllerAnimated(false) { 
            //
            SVProgressHUD.dismiss()
            
            //发布通知 欢迎控制器的通知
            NSNotificationCenter.defaultCenter().postNotificationName(SWrootViewControllerNotification, object: self, userInfo: ["rootVc": "wellcome"])
        }
        
    }
    
    
    @objc private func autoFill() {
        //拼接一段js代码
        let jsString = "document.getElementById('userId').value = '13203338802';" + "document.getElementById('passwd').value = 't21.35814';"
        
        //在webView中执行一段js代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    //MARK: - View
    override func loadView() {
        //替换默认view
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(closeOauth))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(autoFill))
        
        //加载授权网页
        loadOauthView()
        
        //设置代理
        webView.delegate = self
    }
    
    private func loadOauthView() {
        //拼接URL
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        //加载请求
        webView.loadRequest(request)
    }
    
    override func viewDidDisappear(animated: Bool) {
        //
        super.viewDidDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
}

// MARK: - 实现代理方法 监听webView
extension SWOauthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        //
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //
        SVProgressHUD.dismiss()
    }
    
    //过滤URL
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果没有值, 则返回false
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        //能来到这里,说明URL一定有值
        //如果包含该前缀,则返回true
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        //能来到这里,说明URL有值,并且不包含 授权
        //如果不包含 回调地址    过滤掉能来到这里的 所有不包含回调页的地址
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        //能来到这,说明只有包含 回调地址 的URL
        //获取code
        //获取URL中的参数     如果没有参数,返回false
        guard let query = request.URL?.query else {
            return false
        }
        //query一定有值     截取code=之后的字符串
        let code = query.substringFromIndex("code=".endIndex)

        //获取token,完成后关闭控制器
        SWUserAccountViewModel.accessToken(code) { (error) in
            //回到home登录状态
//            SWBaseTableViewController().userLogin = true
            //完成回调代码    关闭授权页面
            self.closeOauth()
        }
        
        //阻止回调地址加载
        return false
    }
    
}
